# coding=utf-8

import json
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.decorators import action

from utils.custom_modelviewset import CustomModelViewSet
from utils.permission import IsAdministratorUser
from utils import response_ok
from apps.log.models import BizLog
from apps.admin import admin_log

from .serializers import WechatAppletSerializer
from apps.WechatApplet.filters import WechatAppletFilter
from apps.WechatApplet.models import WechatApplet
from apps.WechatTp.models import WechatTp


class TemplateListViewSet(APIView):
    permission_classes = [IsAdministratorUser, ]

    def get(self, request):
        tp = WechatTp.getDefault()
        ret = tp.getTemplateList()
        return response_ok(ret)


class WechatAppletViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser, ]
    queryset = WechatApplet.objects.filter()
    serializer_class = WechatAppletSerializer

    def filter_queryset(self, queryset):
        f = WechatAppletFilter(self.request.GET, queryset=queryset)
        return f.qs

    @action(methods=['post'], detail=True)
    def upload_code(self, request, pk):
        # 上传代码
        template_id = request.POST.get('template_id')
        user_version = request.POST.get('user_version')
        user_desc = request.POST.get('user_desc')
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.uploadCode(template_id, user_version, user_desc)
            admin_log(request.user, BizLog.INSERT,u'小程序上传审核代码，id=%d' % app.id, request.POST.dict())
        return response_ok()

    @action(methods=['post'], detail=False)
    def batch_upload_code(self, request):
        # 批量上传代码
        template_id = request.POST.get('template_id')
        user_version = request.POST.get('user_version')
        user_desc = request.POST.get('user_desc')
        app_ids = json.loads(request.POST.get('ids'))

        apps = WechatApplet.objects.filter(id__in=app_ids)
        for app in apps:
            try:
                with transaction.atomic():
                    app.uploadCode(template_id, user_version, user_desc)
            except:
                pass
        admin_log(request.user, BizLog.INSERT, u'小程序批量上传审核代码', request.POST.dict())

        return response_ok()

    @action(methods=['post'], detail=False)
    def refresh_audit_status(self, request):
        # 查询最新一次提交代码的审核状态  多选更新 审核状态
        app_ids = json.loads(request.POST.get('ids'))
        for app_id in app_ids:
            app = WechatApplet.getById(app_id)
            app.refreshAuditStatus()
        return response_ok()

    @action(methods=['post'], detail=True)
    def set_secret(self, request, pk):
        secret = request.POST.get('secret')
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.secret = secret
            app.save()
            admin_log(request.user, BizLog.INSERT, u'设置小程序秘钥, id=%d' % app.id, secret)
        return response_ok()

    @action(methods=['post'], detail=True)
    def set_merchant(self, request, pk):
        tenant_num = request.POST.get('tenant_num')
        tenant_key = request.POST.get('tenant_key')
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.tenant_num = tenant_num
            app.tenant_key = tenant_key
            app.save()
            admin_log(request.user, BizLog.INSERT, u'设置小程序商户号和商户秘钥, id=%d' % app.id)
        return response_ok()

    @action(methods=['post'], detail=False)
    def add_plugin(self, request):
        app_ids = json.loads(request.POST.get('ids'))
        for app_id in app_ids:
            apps = WechatApplet.getById(app_id)
            apps.addPlugin()
        return response_ok()

    @action(methods=['post'], detail=False)
    def release(self, request):
        app_ids = json.loads(request.POST.get('ids'))
        for app_id in app_ids:
            app = WechatApplet.getById(app_id)
            app.releaseApplet()
        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_cert(self, request, pk):
        file = request.FILES.get('file', None)
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.upload_cert_file(file)
            admin_log(request.user, BizLog.INSERT, u'设置小程序企业支付api证书, id=%d' % app.id)
        return response_ok()



